const { exec } = require('../db/index')
const jwt = require('jsonwebtoken')

class UserService {
  // 登陆 ctx.request.body
  async login(ctx) {
    const { username, password } = ctx.request.body;
    let data = await exec(`select * from users where username='${username}' and password='${password}'`)
    // 看他有没有
    if (data.length) {
      let token = jwt.sign({ ...data[0] }, 'key', { expiresIn: '1h' })
      return { code: 0, msg: 'success', token }
    } else {
      return { code: -1, msg: 'fail' }
    }
  }

  async register(ctx) {
    const { username, password, nickname } = ctx.request.body;
    let data = await exec(`select * from users where username='${username}'`)
    if (data.length) {
      return { code: -1, msg: '账号已经被注册了' }
    } else {
      let data = await exec(`insert into users (username, password, nickname) values ('${username}', '${password}', '${nickname}')`)
      console.log(data, '我是注册的数据')
      return { code: 0, msg: 'success' }
    }
  }

  async delete(ctx) {
    const { id } = ctx.query;
    let data = await exec(`delete from blogs where id = ${id}`);
    console.log(data, 'data')
    if (data.affectedRows) {
      return { code: 0, msg: 'success', affectedRows: data.affectedRows }
    } else {
      return { code: -1, msg: '当前删除的id不存在', affectedRows: data.affectedRows }
    }
  }

  async page(ctx) {
    const { page = 0, size = 5 } = ctx.query;
    // 分页总数
    let total = await exec(`select count(id) as num from blogs`)
    // 分页数据
    let data = await exec(`select * from blogs limit ${size} offset ${page * size}`)
    return { code: 0, msg: 'success', total: total[0].num, data }
  }

  async search(ctx) {
    const { keyword } = ctx.query;
    let data = await exec(`select * from blogs where title like '%${keyword}%'`)
    return { code: 0, msg: 'success', data }
  }
}

module.exports = new UserService